<?php

namespace App\Http\Controllers\Api;

use App\ChatRecord;
use Carbon\Carbon;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Storage;
use Intervention\Image\Facades\Image;

class ChatController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request) {
        $message = ChatRecord::where('from_user_id', $request->with_user)
            ->where('to_user_id', $request->current_user)
            ->orWhere('from_user_id', $request->current_user)
            ->where('to_user_id', $request->with_user)
            ->with(['from'])
            ->orderBy('id', 'desc')->limit(30)->get();
        $message = array_reverse($message->toArray());
        $message = json_encode($message);
        ChatRecord::where('to_user_id', $request->current_user)
            ->where('from_user_id', $request->with_user)
            ->update(['read_at' => Carbon::now()]);
        return response("retry:3000\nid:1\ndata:{$message}\n\n")->header('Content-Type', 'text/event-stream')->header('Cache-Control', 'no-cache');
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        //
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        //return $request->file();
        $body = $request->get('body');
        if ($file = $request->file('file')) {
            $ext = $file->getClientOriginalExtension();
            $path = 'images/' . 'chat' . '/'.date('Ym');
            //$thumbPath = $path.'.'.$ext;
            //$image->orientate();
            // $image->encode(70);
           // Storage::disk('public')->put($thumbPath, $image, 'public');
            $path = $request->file('file')->store($path, 'public');
            $path = asset('storage/'. $path);
           // Image::make($path)->widen(100)->save($path);
            $body = "<img  src='{$path}' style='max-width: 100%';>";
        }
        $chat = ChatRecord::create([
            'from_user_id' => $request->get('from'),
            'to_user_id' => $request->get('to'),
            'body' => $body
        ]);
        $chat->from;
        return $chat;
    }

    /**
     * Display the specified resource.
     *
     * @param  \App\ChatRecord  $chatRecord
     * @return \Illuminate\Http\Response
     */
    public function show(ChatRecord $chatRecord)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  \App\ChatRecord  $chatRecord
     * @return \Illuminate\Http\Response
     */
    public function edit(ChatRecord $chatRecord)
    {
        //
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \App\ChatRecord  $chatRecord
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, ChatRecord $chatRecord)
    {
        //
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  \App\ChatRecord  $chatRecord
     * @return \Illuminate\Http\Response
     */
    public function destroy(ChatRecord $chatRecord)
    {
        //
    }

    public function unread()
    {
        $unread = ChatRecord::where("to_user_id", Auth::id())
            ->select(DB::raw('count(*) as count, from_user_id'))
            ->whereNull('read_at')
            ->groupBy('from_user_id')
            ->with('from')
            ->get();
        $read = ChatRecord::where("to_user_id", Auth::id())
            ->select(DB::raw('0 as count, from_user_id'))
            ->whereNotNull('read_at')
            ->groupBy('from_user_id')
            ->with('from')
            ->whereNotIn('from_user_id', $unread->pluck('from_user_id'))
            ->get();

        return array_merge($unread->toArray(), $read->toArray());
    }

    public function unreadCount($to) {
        $count = ChatRecord::where('to_user_id', $to)
            ->whereNull('read_at')
            ->count();
        return response("retry:10000\nid:1\ndata:{$count}\n\n")->header('Content-Type', 'text/event-stream')->header('Cache-Control', 'no-cache');
    }
}
